public class MaxSubarraySum {
    public static void main(String[] args) {
        int[][] testCases = {
            {1, -2, 3, 5, -1},
            {1, -2, 3, -8, 5, 1},
            {1, -2, 3, -2, 5, 1},
            {-1, -2, -3},
            {5, -3, 7}
        };

        for (int[] arr : testCases) {
            int maxSum = maxSubarraySum(arr);
            System.out.print("数组: ");
            printArray(arr);
            System.out.println("  最大子数组和: " + maxSum);
        }
    }

    public static int maxSubarraySum(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }

        int maxSoFar = arr[0];
        int maxEndingHere = arr[0];

        for (int i = 1; i < arr.length; i++) {
            maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
            maxSoFar = Math.max(maxSoFar, maxEndingHere);
        }

        return maxSoFar;
    }

    private static void printArray(int[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if (i < arr.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.print("]");
    }
}